package com.sun.dailyprj.view;


import android.os.CountDownTimer;

import com.sun.dailyprj.util.Logger;

public class NonLineProgressRules{

    private int mInflectPointer; //进度条分段点数，比如三段则有两个拐点
    private int mCurInflectPointer = 0;//当前进度值拐点位置。
    private int mCurProgress = 0;//当前进度值
    private int mMax = 100;
    private int mMin = 0;
    private int mInflectPointerMax;
    private CountDownTimer mCountDownTimer;
    private int mExpectedTime = 5 * 60 * 1000;//5min
    private CountDownTimerCallback mCallback;

    public NonLineProgressRules(int inflectPoint, int expectedTime, int max, int min,
                                CountDownTimerCallback cb) {
        this.mMax = max;
        this.mMin = min;
        if(inflectPoint > mMax || inflectPoint < mMin)
            try{
                throw new Exception("Inflection point number set is not reasonable ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        this.mInflectPointer = inflectPoint;
        this.mExpectedTime = expectedTime;
        this.mCallback = cb;
        mInflectPointerMax = (mMax - mMin) / (mInflectPointer + 1);
        initCountDownTimer();
    }

    public synchronized int calProgress(int progress) {
        if(mCurInflectPointer == progress) {
            //在当前拐点内，无需更新大的进度值
        } else {
            mCurInflectPointer = progress;
            mCurProgress = mCurInflectPointer * mInflectPointerMax;
        }
        if(mCurProgress == mMax) {
            mCountDownTimer.cancel();
        }
        return mCurProgress;
    }

    //默认匀速升级中，获取到某个ecu安装完成后，进度值则直接跳到对应百分比上去，然后再继续慢慢的更新。
    private void initCountDownTimer() {
        long millisInFuture = (mMax - mMin) / (mInflectPointer + 1);
        Logger.debug("millisInFuture:" + millisInFuture + " ;mExpectedTime:" + mExpectedTime);
        mCountDownTimer = new CountDownTimer(mExpectedTime, mExpectedTime / 100){
            @Override
            public void onTick(long millisUntilFinished) {
                int tempPointer = (mCurInflectPointer + 1) * mInflectPointerMax;
                Logger.debug("mCurInflectPointer:" + mCurInflectPointer + " ;mCurProgress:" + mCurProgress);
                if(mCurProgress > tempPointer || mCurProgress == tempPointer) {
                    mCurProgress = tempPointer;
                } else {
                    mCurProgress = mCurProgress + 1;
                }
                Logger.info("onTick() mCurProgress:%d", mCurProgress);
            }

            @Override
            public void onFinish() {
                Logger.info("onFinish() finished");
                mCallback.onFinished();
            }
        };
        mCountDownTimer.start();
    }

    public void celCountDownTimer(){
        if(mCountDownTimer != null) mCountDownTimer.cancel();
    }

    public interface CountDownTimerCallback{
        void onFinished();
    }

}
